package com.gxa.service.impl;

import com.gxa.dto.ResultData;
import com.gxa.mapper.GoodsMapper;
import com.gxa.mapper.GoodsTypeMapper;
import com.gxa.mapper.StockChangeMapper;
import com.gxa.mapper.StockMapper;
import com.gxa.pojo.*;
import com.gxa.service.StockService;
import com.gxa.utils.AppDateUtils;
import com.gxa.utils.Code;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class StockServiceImpl implements StockService {

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsTypeMapper goodsTypeMapper;

    @Autowired
    private StockChangeMapper stockChangeMapper;

    @Override
    public Map<String, Object> stock(int page) {
        //查询库存表
        List<Map<String,Object>> mapList = new LinkedList<>();
        int start,end;
        start = (page-1)*10;
        end = 10;
//        StockExample stockExample = new StockExample();
//        stockExample.createCriteria()
        mapList = stockMapper.stock(start,end);

        //查询库存表条数
        Map<String,Object> map = new HashMap<>();
        StockExample stockExample = new StockExample();
        map.put("count",stockMapper.countByExample(stockExample));
        map.put("stock",mapList);
        return map;
    }

    @Override
    public List<Map<String, Object>> stockSearch(String goodsName) {
        //按照商品名查找商品库存
        List<Map<String,Object>> mapList = new LinkedList<>();
        Map<String,Object> map = new HashMap<>();
        return stockMapper.stockSearch(goodsName);
    }

    @Override
    public Map<String, Object> check(int type,int page) {
        //查询所有的出/入库记录
        int start,end;
        start = (page-1)*10;
        end = 10;
        List<Map<String,Object>> mapList = stockMapper.check(type,start,end);
        //通过state状态来限制查询所有的出/入库记录条数
        StockChangeExample stockChangeExample = new StockChangeExample();
        stockChangeExample.createCriteria().andTypeEqualTo(type).andStateEqualTo(0);
        Map<String,Object> map = new HashMap<>();
        map.put("count",stockChangeMapper.countByExample(stockChangeExample));
        //讲date转化成字符串
        for (Map m:mapList
        ) {
            String time = AppDateUtils.getFormatTime((Date) m.get("time"));
            m.put("time",time);
        }
        map.put("stock",mapList);
        return map;
    }

    @Override
    public Map<String, Object> checkSearch(int type,String goodsName,int page) {
        //根据商品名查询该商品的所有出/入库记录
        page = (page - 1) * 10;
        List<Map<String, Object>> mapList = stockMapper.checkSearch(type,goodsName,page);
        if(mapList.isEmpty()){
            return null;
        }
        //将date转化成字符串
        for (Map map:mapList
        ) {
            String time = AppDateUtils.getFormatTime((Date) map.get("time"));
            map.put("time",time);
        }
        //通过商品名查询id
//        GoodsExample goodsExample = new GoodsExample();
//        goodsExample.createCriteria().andGoodsNameEqualTo(goodsName);
//        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        //通过id和出/入库类型和state（是否真删除）状态来限制查找条数
//        StockChangeExample stockChangeExample = new StockChangeExample();
//        stockChangeExample.createCriteria().andTypeEqualTo(type).andGoodsIdEqualTo(mapList.get(0)).andStateEqualTo(0);
        int count = stockChangeMapper.checkCount(type,goodsName);
        //将数据与条数返回回去
        Map<String, Object> map = new HashMap<>();
        map.put("count",count);
        map.put("mapList",mapList);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData checkAdd(int type, Map<String, String> map, int id) {
        ResultData resultData = new ResultData();
        //通过商品名查找商品信息并插入一条商品信息(限制条件state:0)
        GoodsExample goodsExample = new GoodsExample();
        Goods goods = new Goods();
        goods.setGoodsName(map.get("goodsName"));
        goodsExample.createCriteria().andGoodsNameEqualTo(map.get("goodsName")).andStateEqualTo(0);
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        if(goodsList.isEmpty()){
            resultData.setCode(Code.FALISE);
            resultData.setMsg("没有该商品信息，需要添加");
            return resultData;
        }
        goods = goodsList.get(0);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        // 生产日期
        Date date = null;
        // 出入库时间
        Date date1 = null;
        try {
            if( type == 1){
                date = sdf.parse(map.get("productTime"));
            }
            date1 = new Timestamp(System.currentTimeMillis());
        } catch (ParseException e) {
            resultData.setCode(Code.FALISE);
            resultData.setMsg("时间出错");
            return resultData;
        }

        goods.setProductTime(date);
        goods.setId(null);
        goodsMapper.myInsertSelective(goods);

        //通过商品id查找商品的库存并修改数量
        goodsExample = new GoodsExample();
        goodsExample.createCriteria().andGoodsNameEqualTo(map.get("goodsName"));
        List<Goods> goodsList1 = goodsMapper.selectByExample(goodsExample);
        // 获取goodsID
        List<Integer> goodsIds = new ArrayList<>();
        for (Goods goods1 : goodsList1) {
            goodsIds.add(goods1.getId());
        }

        StockExample stockExample = new StockExample();
        stockExample.createCriteria().andGoodsIdIn(goodsIds);
        List<Stock> stock = stockMapper.selectByExample(stockExample);
        if (stock.isEmpty()) {
            Stock stock1 = new Stock();
            stock1.setGoodsAmount(Integer.parseInt(map.get("num")));
            stock1.setGoodsId(goodsIds.get(0));
            stock1.setStandardAmount(5000);
            stockMapper.insertSelective(stock1);
        }else{
            if (type == 1) {
                stock.get(0).setGoodsAmount(stock.get(0).getGoodsAmount() + Integer.parseInt(map.get("num")));
            }
            else {
                stock.get(0).setGoodsAmount(stock.get(0).getGoodsAmount() - Integer.parseInt(map.get("num")));
            }
            stockMapper.updateByPrimaryKey(stock.get(0));
        }

        //插入一条商品的出入库时间
        StockChange stockChange = new StockChange();
        stockChange.setTime(date1);
        stockChange.setGoodsId(goods.getId());
        stockChange.setAmount(Integer.parseInt(map.get("num")));
        stockChange.setType(type);
        stockChange.setUserId(id);
        stockChange.setState(0);
        stockChangeMapper.insertSelective(stockChange);

        resultData.setCode(200);
        resultData.setMsg("入库成功!");
        return resultData;
    }
    @Override
    public ResultData checkEdit(int type, Map<String, String> map,int id){
        ResultData resultData = new ResultData();
        /*判断是否存在该商品信息*/
        GoodsExample goodsExample =new GoodsExample();
        goodsExample = new GoodsExample();
        goodsExample.createCriteria().andGoodsNameEqualTo(map.get("goodsName"));
        List<Goods> goodsList1 = goodsMapper.selectByExample(goodsExample);
        if (goodsList1.isEmpty()){
            resultData.setCode(Code.FALISE);
            resultData.setMsg("没有该商品信息");
            return resultData;
        }
        //判断时间是否正确
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            if (type == 0) {
                date = sdf.parse(map.get("checkoutTime"));
            }else {
                date = sdf.parse(map.get("checkinTime"));
            }
        } catch (ParseException e) {
            resultData.setCode(Code.FALISE);
            resultData.setMsg("时间出错");
            return resultData;
        }
        //通过商品id去修改商品名
        Goods goods = new Goods();
        goodsExample = new GoodsExample();
        goodsExample.createCriteria().andIdEqualTo(Integer.parseInt(map.get("goodsId")));
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        String goodsName = goodsList.get(0).getGoodsName();
        goods = goodsList.get(0);

//        try {
//            date = sdf.parse(map.get("productTime"));
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        goods.setGoodsName(map.get("goodsName"));
 //       goods.setProductTime(date);
        goods.setShelfLife(goodsList1.get(0).getShelfLife());
        goods.setTypeId(goodsList1.get(0).getTypeId());
        goodsMapper.updateByPrimaryKey(goods);
        //通过商品id查找商品的库存并修改数量
        if(goodsName.equals(goodsList1.get(0).getGoodsName())){
            StockExample stockExample = new StockExample();
            stockExample.createCriteria().andGoodsIdEqualTo(goodsList1.get(0).getId());
            List<Stock> stock = stockMapper.selectByExample(stockExample);
            if (type == 1) {
                stock.get(0).setGoodsAmount(stock.get(0).getGoodsAmount() + Integer.parseInt(map.get("num"))-Integer.parseInt(map.get("amount")));
            }
            else {
                stock.get(0).setGoodsAmount(stock.get(0).getGoodsAmount() - Integer.parseInt(map.get("num"))+Integer.parseInt(map.get("amount")));
            };
            stockMapper.updateByPrimaryKey(stock.get(0));
        }
        else {
            //获取要更新的数量的goodsId
            StockExample stockExample = new StockExample();
            stockExample.createCriteria().andGoodsIdEqualTo(goodsList1.get(0).getId());
            List<Stock> stock = stockMapper.selectByExample(stockExample);
            //获取未更新的数量的goodsId
            goodsExample = new GoodsExample();
            goodsExample.createCriteria().andGoodsNameEqualTo(goodsName);
            List<Goods> goodsList2 = goodsMapper.selectByExample(goodsExample);
            stockExample = new StockExample();
            stockExample.createCriteria().andGoodsIdEqualTo(goodsList2.get(0).getId());
            List<Stock> stock1 = stockMapper.selectByExample(stockExample);

            if (type == 1) {
                stock.get(0).setGoodsAmount(stock.get(0).getGoodsAmount() + Integer.parseInt(map.get("num")));
                stock1.get(0).setGoodsAmount(stock1.get(0).getGoodsAmount() - Integer.parseInt(map.get("num")));
            }
            else {
                stock.get(0).setGoodsAmount(stock.get(0).getGoodsAmount() - Integer.parseInt(map.get("num")));
                stock1.get(0).setGoodsAmount(stock1.get(0).getGoodsAmount() + Integer.parseInt(map.get("num")));
            };
            stockMapper.updateByPrimaryKey(stock.get(0));
            stockMapper.updateByPrimaryKey(stock1.get(0));
        }


        //更新一条商品的出入库时间
        StockChangeExample stockChangeExample = new StockChangeExample();
//        stockChangeExample.createCriteria().andGoodsIdEqualTo(Integer.parseInt(map.get("goodsId")));
        stockChangeExample.createCriteria().andIdEqualTo(Integer.parseInt(map.get("id")));
        List<StockChange> stockChangeList = stockChangeMapper.selectByExample(stockChangeExample);
        StockChange stockChange = new StockChange();
        stockChange = stockChangeList.get(0);
        stockChange.setTime(date);
        stockChange.setUserId(id);
        stockChange.setAmount(Integer.parseInt(map.get("num")));
        stockChangeMapper.updateByExample(stockChange,stockChangeExample);
        resultData.setCode(Code.SUCCESS);
        resultData.setMsg("编辑成功");
        return resultData;
    }

    @Override
    public void checkDelete(int id,int userId) {
        StockChangeExample stockChangeExample = new StockChangeExample();
        stockChangeExample.createCriteria().andIdEqualTo(id);
        List<StockChange> stockChangeList = stockChangeMapper.selectByExample(stockChangeExample);
        stockChangeList.get(0).setState(1);
        stockChangeList.get(0).setUserId(userId);
        stockChangeMapper.updateByPrimaryKey(stockChangeList.get(0));
        return;
    }
}
